package com.lagou.work.task03.angel.jobService.impl.dome;

import com.lagou.work.task03.angel.job.impl.JobServiceImpl;
import com.lagou.work.task03.angel.jobService.masterService.JobMasterBase;
import com.lagou.work.task03.angel.utils.IOUtil;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author：dingyuan
 * @date：2022.4.7 19:46
 * @description：继承 master端功能抽象类，自定义实现分布式计算master端功能
 */
public class JobMasterDemo extends JobMasterBase {
    private static final String KEY_SERVER_SOCKET = "server.socket";
    private static final String KEY_CLIENT_SOCKET = "client.socket";

    // 启动client Job
    public static void main(String[] args) throws Exception {
        new JobMasterDemo().run(args);
    }

    @Override
    public void handleJob(ArrayList<Map<String, String>> configMap, List<Integer> port) throws Exception {
        List<Object> serverSockets = null;
        List<Object> clientSockets = null;
        Socket accept = null;
        JobServiceImpl jobService = new JobServiceImpl();
        Map<String, List<Object>> jobManageMaster = null;
        try {
            jobManageMaster = jobService.getJobManageMaster(port , null);
            serverSockets = jobManageMaster.get(KEY_SERVER_SOCKET);
            ServerSocket serverSocket = (ServerSocket) serverSockets.get(0);
            while (true){
                System.out.println("Master端等待Client连接请求...");
                accept = serverSocket.accept();
                System.out.println("Client" + accept.getInetAddress() + "连接成功，等待发送信息...");
                jobManageMaster = jobService.getJobManageMaster(null,configMap);
                clientSockets = jobManageMaster.get(KEY_CLIENT_SOCKET);
                new Thread(new MasterJobRunnable(accept,clientSockets)).start();
            }

        } catch (Exception e) {

            e.printStackTrace();

        }finally {
            IOUtil.close(serverSockets,clientSockets,null,null,null,null,null);
        }
    }


    public ByteArrayOutputStream receiveClientFile(Socket accept){

        InputStream inputStream = null;
        PrintStream printStream = null;
        ByteArrayOutputStream byteArrOutStream = null;
        try {
            inputStream = accept.getInputStream();
            // 准备本地接收的输出流
            byteArrOutStream =(ByteArrayOutputStream) IOUtil.handleIOStream(inputStream, new ByteArrayOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtil.close(null, inputStream, null, printStream);
        }
        return byteArrOutStream;
    }

    /**
     * Master端对Client端发生来Job进行处理
     */
    class MasterJobRunnable implements Runnable{

        public Socket serverAccept;
        public List<Object> clientSockets;

        public MasterJobRunnable() {
        }

        public MasterJobRunnable(Socket serverAccept, List<Object> clientSockets) {
            this.serverAccept = serverAccept;
            this.clientSockets = clientSockets;
        }


        @Override
        public void run() {
            ByteArrayOutputStream byteArrayOutputStream =null;
            InputStream in = null;
            try {

                byteArrayOutputStream = receiveClientFile(serverAccept);
                for (Object clientSocket : clientSockets) {
                    synchronized (this){
                        in = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                        Socket client = (Socket)clientSocket;
                        IOUtil.handleIOStream(in, client.getOutputStream());
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                IOUtil.close(null, null, null, null, byteArrayOutputStream);
            }

        }
    }
}
